package com.future.cb.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.future.cb.common.utils.TokenUtil;
import com.future.cb.dao.entity.SysUser;
import com.future.cb.dao.repository.SysUserRepository;

import net.minidev.json.JSONObject;

@Service
public class AuthenticationService {
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysUserRepository sysUserRepository;
	
	@Value("${tokenexp}")
	private Long tokenexp;
	
	@Autowired
	private TokenUtil tokenUtil;
	
	/**
	 * 获取token
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public String getToken(String username, String password) {
		this.sysUserService.validateUser(username, password);
		SysUser sysUser = this.sysUserRepository.findByUsername(username);
		Map<String, Object> payloadMap = new HashMap<String, Object>();
		Long exp = new Date().getTime() + this.tokenexp * 1000;
		payloadMap.put("exp", exp);
		payloadMap.put("userid", sysUser.getUserid());
		String token = this.tokenUtil.creatToken(payloadMap);
		return token;
	}
	
	/**
	 * 刷新token,先验证原来的token的合法性，然后生成新的
	 * @param token
	 * @return
	 */
	public String refreshtoken(String token) {
		JSONObject result = this.tokenUtil.parseToken(token);
		String userid = result.getAsString("userid");
		Long exp = new Date().getTime() + this.tokenexp * 1000;
		Map<String, Object> payloadMap = new HashMap<String, Object>();
		payloadMap.put("exp", exp);
		payloadMap.put("userid", userid);
		String tokennew = this.tokenUtil.creatToken(payloadMap);
		return tokennew;
	}

}
